package club.worldbang.spring.prototype.advanced;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

/**
 * 孙悟空
 */
public class SunWuKong extends Monkey implements Cloneable,Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8610253691073981939L;
	// 武器
	private GoldRingedStaff goldRingedStaff;

	public SunWuKong() {
		this.goldRingedStaff = new GoldRingedStaff();
		this.setBirthday(new Date());
		this.setHeight(169);
		this.setWeight(60);
	}

	public GoldRingedStaff getGoldRingedStaff() {
		return goldRingedStaff;
	}

	public void setGoldRingedStaff(GoldRingedStaff goldRingedStaff) {
		this.goldRingedStaff = goldRingedStaff;
	}

	//分身使用
	public void change() throws CloneNotSupportedException {
		SunWuKong copy = (SunWuKong) clone();
		System.out.println("悟空生日:" + this.getBirthday().getTime());
		System.out.println("分身悟空生日:" + copy.getBirthday().getTime());
		System.out.println("分身和悟空是否同一个:" + (copy == this));
		System.out.println("用的金箍棒:" + (this.goldRingedStaff == copy.goldRingedStaff));
	}

	// 分身技能
	public Object clone() {
		//深克隆
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;

		try {
			// 序列化
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);

			// 反序列化
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			SunWuKong sek = (SunWuKong) ois.readObject();
			sek.setBirthday(new Date());
			return sek;
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return null;
	}
}
